<template>
  <div class="loginbox">
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <div class="login">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section>
        <a
          href="javascript:;"
          :class="{ active: isShowLogin }"
          @click="isShowLogin = true"
          >手机号码登录</a
        >
        |
        <a
          href="javascript:;"
          :class="{ active: !isShowLogin }"
          @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phonelogin" v-show="isShowLogin">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="PhoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgarr"
              :accuracy="10"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="dxcode"
            />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ count }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrlogin" v-show="!isShowLogin" id="weixin">
          微信扫码盒子
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { SendSMSAPI, PhoneReginAPI,BindingApi,} from "@/request/api.js";
import { validatePhoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowLogin: true,
      msg: "向右滑动",
      imgarr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
      ],
      //手机号初始值
      PhoneNumber: "",
      //倒计时初始值
      count: 6,
      isShowCount: false,
      dxcode: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
    }),
    ...mapActions({
      asyncShowToast: "showToast/asyncShowToast",
      asyncChangeUserInfo:"userInfo/asyncChangeUserInfo"
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //获取验证码
    // 定义toVerify()来帮忙处理验证手机号和验证滑块,相当于招一个打工仔帮你打工
    toVerify() {
      if (!validatePhoneNumber(this.PhoneNumber)) {
        this.asyncShowToast({
          isShow: true,
          msg: "请输入正确的手机号",
          type: "error",
        });
        return;
      }
      //2.2.判断清块验证码 如果校验不通过 需要提示 需要return
      //当msg是'再试一次' || '向右滑动' 都需要提示请滑块滑动验证码
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncShowToast({
          isShow: true,
          msg: "请滑动滑块验证码",
          type: "error",
        });
        return;
      }
      //如果这里不给return true的话,默认值为undefined 就return停止执行了
      return true;
    },
    async getCode() {
      //       11位手机号。刘刚时每一位都提供校验规则 13566669999
      // ^ 以 ． . 廾 头
      // $ 以···结尾
      // 1 %反者
      // [ e1456879] 个 · 2不通过。
      // [ o - o] : o llo 之 (m)
      // \d == [ o-9]
      // {n} : 我示校验n次
      // .test（验证的字符申） 如果通过 返回return ， 否则返回false
      //1. 判断手机号-- 如果校验不通过 需要提示 需要return
      // let reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      // console.log(reg.test(this.PhoneNumber));
      // if (!reg.test(this.PhoneNumber)) {
      //   alert("请输入正确的手机号");
      //   return;
      // }
      // if (!validatePhoneNumber(this.PhoneNumber)) {
      //   alert("请输入正确的手机号码");
      //   return;
      // }
      // //2.2.判断清块验证码 如果校验不通过 需要提示 需要return
      // //当msg是'再试一次' || '向右滑动' 都需要提示请滑块滑动验证码
      // if (this.msg == "再试一次" || this.msg == "向右滑动") {
      //   alert("请滑块滑动验证码");
      //   return;
      // }
      if (!this.toVerify()) return;
      //3．获取验证码（发请求给后台），页面需要倒计时效果。
      let res = await SendSMSAPI({
        phone: this.PhoneNumber,
      });
      if (!res) return; //如果res为undefined
      if (res.code == 0) {
        // 页面需要倒计时(循环-定时器  递减数字-count)
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            // 停止定时器,还原count值
            clearInterval(timer);
            this.count = 6;
            this.isShowCount = false;
          }
        }, 1000);
      }

      //页面需要倒计时效果 （循环-定时器I递减数字-count）
      //问题:连续点击，会增加多个定时器。！！！！
      //解决1：禁用按钮
      //解决2: 让定时器代码只执行一次！（定时器一执行 隐藏当前按钮，显示另一个没有事件的按钮）
    },
    //点击事件
    async submitFn() {
      // let flag = this.toVerify();
      // console.log("flag", flag);
      // if (!flag) return;
      if (!this.toVerify()) return;
      if (this.dxcode.trim() == "") {
        this.asyncShowToast({
          isShow: true,
          msg: "请输入验证码",
          type: "error",
        });
        return;
      }
      let res = null;
      let uuid = localStorage.getItem('uuid')
      if(uuid){
        console.log("发送关联请求");
         res = await BindingApi({
          verifyCode: this.dxcode,
          phone: this.PhoneNumber,
          uuid
         })
      }
      else{
        console.log("发送普通请求");
        res = await PhoneReginAPI({
          verifyCode: this.dxcode,
          phone: this.PhoneNumber,
        });
      }
      console.log(res);
      if (!res) return;
       this.asyncShowToast({
        isShow: true,
        msg: "登陆成功",
        type: "success",
      });
      // 2.隐藏登录框
      this.changeIsShowLoginModal(false);
      // 3.存储token （登录凭证，后续用户请求信息需要用到）
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 4.切换按钮（显示购物车按钮）
      this.changeIsLogined(true);
      // 5.删除uuid
       if (uuid) {
        localStorage.removeItem("uuid");
      }
      // let userres = await UserProfilesAPI();
      // console.log(userres);
      this.asyncChangeUserInfo();
    },
    showQrCode() {
      this.isShowLogin = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.loginbox {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      background: url("../assets/img/close.png");
      width: 22px;
      height: 22px;
    }
    section {
      line-height: 40px;
      text-align: center;
      padding-top: 40px;
      a {
        text-decoration: none;
        color: #c0c0c0;
        &.active {
          color: #0c0c0c;
        }
      }
    }
    .content {
      width: 350px;
      margin: 0 auto;
      text-align: center;
      // background-color: #fcf;
      padding: 0;
      .phonelogin {
        margin-top: 20px;
        .row {
          display: flex;
          height: 45px;
          margin-bottom: 20px;
          input {
            text-indent: 1em;
            flex: 1;
            height: 45px;
          }
          .btn {
            background: rgb(10, 50, 142);
            color: #fff;
            border: none;
          }
          .btncode {
            margin-left: 10px;
            height: 50px;
            width: 80px;
          }
          .btnlogin {
            width: 100%;
            height: 45px;
          }
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>